//
//  NewEventViewController.swift
//  YOKO
//
//  Created by Zoe_G on 16/5/12.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import UIKit
import RealmSwift

class NewEventViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NewEventCellDelegate, EventTypeSelectedCellDelegate ,DatePickerDalegate, UITextViewDelegate, UITextFieldDelegate, ReminderCellDelegate{

    var event: Event? = nil
    
    //cell中的需要控制的组件
    var titleTextField: UITextField! = nil
    var typeBtn: UIButton! = nil
    var descriptionTextView: UITextView! = nil
    var locationTextField: UITextField! = nil
    var wholeDaySwitchBtn: UIButton! = nil
    var endDateSwitchBtn: UIButton! = nil
    var startDateBtn: UIButton! = nil
    var startTimeBtn: UIButton! = nil
    var endDateBtn: UIButton! = nil
    var endTimeBtn: UIButton! = nil
    
    //组件状态
    var isSelectingStartDate: Bool = false
    var isSelectingEndDate: Bool = false
    var isSelectingReminder: Bool = false
    
    //是否属于编辑状态
    var editState = false
    
    var eventType = 0
    
    let dateFormate = NSDateFormatter()
    let timeFormate = NSDateFormatter()
    
    var startDate: NSDate = NSDate() {
        didSet {
            if (startDateBtn != nil) && (startTimeBtn != nil){
                startTimeBtn.setTitle(timeFormate.stringFromDate(startDate), forState: .Normal)
                startDateBtn.setTitle(dateFormate.stringFromDate(startDate), forState: .Normal)
            }
        }
    }
    var endDate: NSDate = NSDate(){
        didSet {
            if (endDateBtn != nil) && (endTimeBtn != nil){
        
                endDateBtn.setTitle(dateFormate.stringFromDate(endDate), forState: .Normal)
                endTimeBtn.setTitle(timeFormate.stringFromDate(endDate), forState: .Normal)
            }
        }
    }
    
    var reminders: String = "0" {
        didSet {
            self.setReminderTitle()
        }
    }
    
    func setReminderTitle() {
        var reminderString = ""
        for i in 0...reminderTitles.count-1 {
            if ((1 << i) & Int(reminders)!) != 0 {
                reminderString = reminderString + reminderTitles[i]
            }
        }
        let length = NSString.init(string: reminderString).length
        
        let stringAttr = NSMutableAttributedString.init(string: reminderString + "提醒")
        stringAttr.addAttribute(NSForegroundColorAttributeName, value: YOKOColor.TypeColors[1], range: NSMakeRange(0, length))
        notifyCell.cellTitleLabel?.attributedText = stringAttr
    }
    
    //tableViewData
    lazy var headViewTitles = ["设置事件", "设置时间", "更多", "删除"]
    lazy var cellTitles = [["标题", "备注", "地点"], ["全天", "开始", "结束"], ["提醒"], ["删除"]]
    lazy var reminderTitles = ["事件发生时  ","5分钟前  ","15分钟前  ","30分钟前  ","1小时前  ","1天前  ","2天前  ","一周前  "]

	@IBOutlet weak var eventVIewTableView: UITableView!
    
    lazy var titleCell: NewEventTextFieldCell = {
        
        let cell = NSBundle.mainBundle().loadNibNamed("NewEventTextFieldCell", owner: self, options: nil).last as! NewEventTextFieldCell
        cell.rightBtnImgName = "标签"
        cell.iconLineType = CellLineType.LineFirst
        cell.delegate = self
        return cell
    }()
    
    lazy var descriptionCell: NewEventTextViewCell = {
        
        let cell = NSBundle.mainBundle().loadNibNamed("NewEventTextViewCell", owner: self, options: nil).last as! NewEventTextViewCell
        cell.iconLineType = CellLineType.LineMiddle
        cell.delegate = self
        
        return cell
    }()
    
    lazy var locationCell: NewEventTextFieldCell = {
        let cell = NSBundle.mainBundle().loadNibNamed("NewEventTextFieldCell", owner: self, options: nil).last as! NewEventTextFieldCell
        cell.rightBtnImgName = ""
        cell.isRightBtnAction = false
        cell.iconLineType = CellLineType.LineLast
        cell.delegate = self
        return cell
    }()
    
    lazy var wholeDayCell: NewEventNarmolCell = {
        let cell =  NSBundle.mainBundle().loadNibNamed("NewEventNarmolCell", owner: self, options: nil).last as! NewEventNarmolCell
        cell.hasSwitchBtn = true
        
        return cell
    }()
    
    lazy var startTimeCell: NewEventTimeCell = {
        let cell = NSBundle.mainBundle().loadNibNamed("NewEventTimeCell", owner: self, options: nil).last as! NewEventTimeCell
        cell.dateBtn.tag = 0
        cell.timeBtn.tag = 1
        
        return cell
    }()
    
    lazy var endTimeCell: NewEventTimeCell = {
        let cell = NSBundle.mainBundle().loadNibNamed("NewEventTimeCell", owner: self, options: nil).last as! NewEventTimeCell
        cell.hasSwitchBtn = true
        cell.dateBtn.tag = 0
        cell.timeBtn.tag = 1
        cell.clipsToBounds = true
        
        
        return cell
    }()
    
    lazy var notifyCell: NewEventNarmolCell = {
        let cell = NSBundle.mainBundle().loadNibNamed("NewEventNarmolCell", owner: self, options: nil).last as! NewEventNarmolCell
        cell.iconLineType = CellLineType.LineNone
//        self.setReminderTitle()
        return cell
    }()
    
//    lazy var calandarCell: NewEventNarmolCell = {
//        let cell = NSBundle.mainBundle().loadNibNamed("NewEventNarmolCell", owner: self, options: nil).last as! NewEventNarmolCell
//        cell.iconLineType = CellLineType.LineLast
//        
//        return cell
//    }()
    
    lazy var typeCell: EventTypeSelectCell = {
        let cell = NSBundle.mainBundle().loadNibNamed("EventTypeSelectCell", owner: self, options: nil).last as! EventTypeSelectCell
        cell.delegate = self
        return cell
    }()
    
    lazy var datePickerCell: NewEventDatePickerCell = {
        let cell =  NewEventDatePickerCell(style: UITableViewCellStyle.Default, reuseIdentifier: "NewEventDatePickerCell")
        cell.delegate = self
        return cell
    }()
    
    lazy var deleteCell: UITableViewCell = {
        let cell = NSBundle.mainBundle().loadNibNamed("NewEventDeleteCell", owner: self, options: nil).last as! UITableViewCell
        let deleteButton = cell.contentView.subviews.filter{$0 is UIButton}.last! as! UIButton
        deleteButton.addTarget(self, action: #selector(NewEventViewController.deleteButtonHandler), forControlEvents: .TouchUpInside)
        return cell
    }()
    
    lazy var reminderCell: NewEventRemindersSelectedCell = {
        let cell = NSBundle.mainBundle().loadNibNamed("NewEventRemindersSelectedCell", owner: self, options: nil).last as! NewEventRemindersSelectedCell
        
        cell.delegate = self
        return cell
    }()
    
    var isSelectingType: Bool = false
    var isSelectingTime: Bool = false
    
    var timeCellHeight: CGFloat = 52.0 {
        didSet {
            self.eventVIewTableView.reloadRowsAtIndexPaths([NSIndexPath.init(forRow: 1, inSection: 0)], withRowAnimation: .None)
        }
    }
    
    var textViewCellHeight: CGFloat = 52.0 {
        didSet {
            self.updateCell()
        }
    }
    var typeCellHeight: CGFloat = 72.0
    var normalCellHeight: CGFloat = 52.0
    var reminderCellHeight: CGFloat = 60.0
    var datePickerCellHeight: CGFloat = 135.0
    var reminderSelectedCellHeight: CGFloat = 35.0
    
    var resignTapGesture: UITapGestureRecognizer!
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
    func updateCell() {
        
        self.eventVIewTableView.beginUpdates()
        self.eventVIewTableView.endUpdates()
    }
    
    override func viewDidLayoutSubviews() {
        
        if editState {
            updateUIForEvent()
        }
    }
    
	override func viewDidLoad() {
		super.viewDidLoad()
        self.eventVIewTableView.backgroundColor = UIColor.whiteColor()
		// Do any additional setup after loading the view.
       
        dateFormate.dateFormat = "YYYY.MM.dd"
        timeFormate.dateFormat = "HH:mm"
        
        setNavigationBarItem()
        
		self.eventVIewTableView.delegate = self
		self.eventVIewTableView.dataSource = self
        self.eventVIewTableView.separatorStyle = .None

        //添加点击取消所有的textField和textView的键盘的手势
        resignTapGesture = UITapGestureRecognizer(target: self, action: #selector(NewEventViewController.resignTapGestureHandler))
        
        self.titleTextField = titleCell.textField
        self.descriptionTextView = descriptionCell.textView
        self.locationTextField = locationCell.textField
        self.wholeDaySwitchBtn = wholeDayCell.switchBtn
        self.endDateSwitchBtn = endTimeCell.switchBtn
        self.startDateBtn = startTimeCell.dateBtn
        self.startTimeBtn = startTimeCell.timeBtn
        self.endDateBtn = endTimeCell.dateBtn
        self.endTimeBtn = endTimeCell.timeBtn
        
        //设置初始时间，结束大开始一小时
        startDate = NSDate()
        let comp = NSDateComponents()
        comp.hour = 1
        endDate = startDate.add(comp)
        
        
	}
    
    override func viewWillAppear(animated: Bool) {
//        setReminderTitle()
    }
    
    func setNavigationBarItem() {
        let cancelBtn = UIButton(type: .Custom)
        cancelBtn.setImage(UIImage(named: "nav_icon_cancel"), forState: .Normal)
        cancelBtn.frame = CGRectMake(0.0, 0.0, 20.0, 20.0)
        cancelBtn.addTarget(self, action: #selector(self.back), forControlEvents: .TouchUpInside)
        
        let yesBtn = UIButton(type: .Custom)
        yesBtn.setImage(UIImage(named: "nav_icon_yes"), forState: .Normal)
        yesBtn.frame = CGRectMake(0.0, 0.0, 20.0, 20.0)
        yesBtn.addTarget(self, action: #selector(self.addNewEvent), forControlEvents: .TouchUpInside)
        
        let titleLabel = UILabel()
        titleLabel.textColor = UIColor.whiteColor()
        titleLabel.textAlignment = .Left
        titleLabel.font = UIFont.systemFontOfSize(18.0)
        titleLabel.frame = CGRectMake( 0, 0, 70.0, 20.0)
        titleLabel.text = "新建事件"
        
        self.navigationItem.titleView = titleLabel
        self.navigationItem.setLeftBarButtonItems([UIBarButtonItem(customView: cancelBtn)], animated: false)
        self.navigationItem.setRightBarButtonItems([UIBarButtonItem(customView: yesBtn)], animated: false)
    }
    
    func back(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    
    func addNewEvent() {
        
        if self.titleTextField.text == "" {
            return
        }
        
        if self.endDate < self.startDate && self.endDateSwitchBtn.selected == true {
            print("\(#function) --> Cannot init a event with the end date is earlier than the start date")
            return
        }
        //给开始时间和结束时间赋值： 1、全天事件设置为这一天的1s 2、零点整点时间设置为0：01 3、其余开始时间结束时间秒数都为0
        let cal = NSCalendar.currentCalendar()
        //为了去掉秒数
        if self.startDate.second != 0 {
            self.startDate = cal.nextDateAfterDate(self.startDate, matchingUnit: .Second, value: 0, options: [.MatchNextTime ,.SearchBackwards])!
        }
        if self.endDate.second != 0{
            self.endDate = cal.nextDateAfterDate(self.endDate, matchingUnit: .Second, value: 0, options: [.MatchNextTime ,.SearchBackwards])!
        }
//        self.startDate = cal.nextDateAfterDate(self.startDate, matchingHour: startDate.hour, minute: startDate.minute, second: 1, options: .MatchNextTime)!
//        self.endDate = cal.nextDateAfterDate(self.endDate, matchingHour: endDate.hour, minute: endDate.minute, second: 1, options: .MatchNextTime)!
        
        if self.wholeDaySwitchBtn.selected {
            let comp = NSDateComponents()
            comp.second = 1
            if self.startDate.hour == 0 && self.startDate.second == 0 {
                self.startDate.add(comp)
            }else {
                self.startDate = cal.nextDateAfterDate(self.startDate, matchingHour: 0, minute: 0, second: 1, options: [.MatchNextTime ,.SearchBackwards])!
            }
            
            if self.endDate.hour == 0 && self.endDate.second == 0 {
                self.endDate.add(comp)
            }else {
                self.endDate = cal.nextDateAfterDate(self.endDate, matchingHour: 0, minute: 0, second: 1, options: [.MatchNextTime ,.SearchBackwards])!
            }
        }
        if !endDateSwitchBtn.selected {
            self.endDate = self.startDate
        }
        
        if self.startDate.hour == 0 && self.startDate.minute == 0 && self.startDate.second == 0 {
            let comp = NSDateComponents()
            comp.second = 1
            self.startDate = self.startDate.add(comp)
        }
        
        if self.endDate.hour == 0 && self.endDate.minute == 0 && self.endDate.second == 0 {
            let comp = NSDateComponents()
            comp.second = 1
            self.endDate = self.endDate.add(comp)
        }
        
        if editState == false {
            event = Event()
            event?.reminders = self.reminders
            event?.summary = self.titleTextField.text!
            event?.descriptions = self.descriptionTextView.text
            event?.location = self.locationTextField.text!
            event?.wholeDayEvent = self.wholeDaySwitchBtn.selected
            event?.timeBegin = self.startDate
            event?.timeEnd = self.endDate
            event?.type = self.eventType
            event?.localId = Int(NSDate().timeIntervalSince1970 * 1000)
            event?.calendarId = NSUserDefaults.getCurrentCalendarId()
            
            try! uiRealm.write({
                uiRealm.add(event!)
                NSLog("newEvent localId = %i", event!.localId)
            })
            
            //处理事件的提醒
            if let fireDates = AlarmController.updateNotificationFireDate(event!){
                if !fireDates.isEmpty{
                    AlarmController.notificationFirstSet(fireDates, event: event!)
                }
                
            }
            
            //添加全天事件的提醒
            if event!.wholeDayEvent{
                let fireDates = [event!.timeBegin.add(0, months: 0, weeks: 0, days: 0, hours: 8, minutes: 0, seconds: 0, nanoseconds: 0)]
                AlarmController.notificationFirstSet(fireDates, event: event!)
            }

            let api = ApiSync()
            api.updateEventToService(event!, isAdd: true, calendarId: NSUserDefaults.getCurrentCalendarId(), callback: {
                (response, error) in
                if (response != nil && response!["result"] as! Bool == true) {
                    print(response)
                    try! uiRealm.write({
                        self.event!.uuid = response!["data"]!["uuid"] as! String
                        self.event!.version = response!["data"]!["version"] as! Int
                        self.event!.calendarId = NSUserDefaults.getCurrentCalendarId()
                        self.event!.etag = response!["data"]!["etag"] as! String
                    })
                }
            })
        }
        else {
            if let eventFromDataBase = uiRealm.objects(Event).filter("localId = %@", event!.localId).last {
                
                try! uiRealm.write {
                    eventFromDataBase.summary = self.titleTextField.text!
                    eventFromDataBase.descriptions = self.descriptionTextView!.text
                    eventFromDataBase.location = self.locationTextField.text!
                    eventFromDataBase.wholeDayEvent = self.wholeDaySwitchBtn.selected
                    eventFromDataBase.timeBegin = self.startDate
                    eventFromDataBase.timeEnd = self.endDate
                    eventFromDataBase.type = self.eventType
                    eventFromDataBase.reminders = self.reminders
                }
                
                //Reminders 
                if let fireDates = AlarmController.updateNotificationFireDate(eventFromDataBase){
                    if !fireDates.isEmpty{
                        AlarmController.updateAlarmWithEvent(fireDates, event: eventFromDataBase)
                    }
                }
                let api = ApiSync()
                api.updateEventToService(eventFromDataBase, isAdd: false, calendarId: NSUserDefaults.getCurrentCalendarId(), callback: {
                    (response, error) in
                    if (response != nil && response!["result"] as! Bool == true) {
                        print(response)
                        try! uiRealm.write({
                            eventFromDataBase.calendarId = NSUserDefaults.getCurrentCalendarId()
                            eventFromDataBase.etag = response!["data"]!["etag"] as! String
                        })
                    }
                })
            }
            else {
                print("\(#function) --> Cannot find event from database")
            }
        }
        
        self.back()
    }
    
    func updateUIForEvent() {
        /**
         仅仅用在处于editState编辑状态的时候，接受到事件event并且刷新UI
         */
        guard editState == true && event != nil else { return }
        
        self.titleTextField.text = event!.summary
        if event!.descriptions != "" {
            self.descriptionTextView.backgroundColor = UIColor.whiteColor()
            self.descriptionTextView.text = event!.descriptions
            let textHeight = NSString(string: event!.descriptions).boundingRectWithSize(CGSizeMake(self.descriptionTextView.bounds.width, 9999), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(16.0)], context: nil).size.height
            
            //改变cell高度
            self.descriptionCell.textViewHeightConstraint.constant = textHeight > 30 ? textHeight+10 : 30
            
            self.textViewCellHeight = CGFloat(Int(textHeight))+20
        }
        self.locationTextField.text = event!.location
        self.wholeDaySwitchBtn.selected = event!.wholeDayEvent
        self.swithWholeDay(self.wholeDaySwitchBtn.selected)
        self.startDate = event!.timeBegin
        self.endDate = event!.timeEnd
        self.endDateSwitchBtn.selected = (self.endDate != self.startDate)
        self.switchEndDate(self.endDateSwitchBtn.selected)
        self.eventType = event!.type
        self.reminders = (event?.reminders)!
        setReminderTitle()
//        self.updateCell()
    }

	// MARK: - UITableViewDataSource
	func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		return cellTitles[section].count
	}

	func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        if self.editState { return headViewTitles.count }
        else {
            return headViewTitles.count - 1
        }
    }

	func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
		let headerView = UIView()
		headerView.frame = CGRectMake(0, 0, screenWidth, 50)
        headerView.backgroundColor = UIColor.whiteColor()

		return headerView
	}

	func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let section = indexPath.section
        let row = indexPath.row
        let cellId = cellTitles[section][row]
        
        var cell: NewEventViewBasicCell!
        
        switch cellId {
        case "type":
            return typeCell
        case "datePicker":
            
            return datePickerCell
        case "标题":
            cell = titleCell
        case "备注":
            cell = descriptionCell
        case "地点":
            cell = locationCell
        case "全天":
            cell = wholeDayCell
        case "开始":
            cell = startTimeCell
            startDateBtn.addTarget(self, action: #selector(self.selectingStartDate(_:)), forControlEvents: .TouchUpInside)
            startTimeBtn.addTarget(self, action: #selector(self.selectingStartDate(_:)), forControlEvents: .TouchUpInside)
        case "结束":
            cell = endTimeCell
            endTimeBtn.addTarget(self, action: #selector(self.selectingEndDate(_:)), forControlEvents: .TouchUpInside)
            endDateBtn.addTarget(self, action: #selector(self.selectingEndDate(_:)), forControlEvents: .TouchUpInside)
        case "提醒":
            cell = notifyCell
        case "reminder":
            reminderCell.tableViewData = reminderTitles
            reminderCell.selectionStyle = .None
            reminderCell.selectedReminders = Int(self.reminders)!
            return reminderCell
        case "删除":
            return deleteCell
        default:
            return UITableViewCell()
        }
        
        cell.imgName = cellId
        cell.cellTitle = cellId
        cell.delegate = self

        return cell
		
	}
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let section = indexPath.section
        let row = indexPath.row
        
        if cellTitles[section][row] == "datePicker" {
           return datePickerCellHeight
        }        
        if cellTitles[section][row] == "type" {
            return typeCellHeight
        }
        if cellTitles[section][row] == "备注" {
            return textViewCellHeight
        }
        if cellTitles[section][row] == "结束" {
            return timeCellHeight
        }
        
        if cellTitles[section][row] == "提醒" {
            return reminderCellHeight
        }
        
        if cellTitles[section][row] == "reminder" {
            return reminderSelectedCellHeight*CGFloat(reminderTitles.count) + 10
        }
        
        return normalCellHeight
        
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.section == 2 && indexPath.row == 0 {
            //选中提醒cell时
            isSelectingReminder = !isSelectingReminder
            
            if isSelectingReminder {
                self.cellTitles[2].insert("reminder", atIndex: 1)
                self.eventVIewTableView.insertRowsAtIndexPaths([NSIndexPath.init(forRow: 1, inSection: 2)], withRowAnimation: .Top)
                self.eventVIewTableView.scrollToRowAtIndexPath(NSIndexPath.init(forRow: 1, inSection: 2), atScrollPosition: .Bottom, animated: true)
            } else {
                self.reminders = String (reminderCell.selectedReminders)
                self.cellTitles[2].removeAtIndex(1)
                self.eventVIewTableView.deleteRowsAtIndexPaths([NSIndexPath.init(forRow: 1, inSection: 2)], withRowAnimation: .Top)
            }
        }
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 15.0
    }
    
    //MARK: - NewEventCellDelegate
    func textViewCellHeightDidChange(cellHeight: CGFloat) {
        self.textViewCellHeight = cellHeight
    }
    
    func timeCellHeightDidChange(cellHeight: CGFloat) {
        self.timeCellHeight = cellHeight
    }
    
//    func reminderCellHeightDidChange(cellHeight: CGFloat) {
//        self.reminderCellHeight = cellHeight
//    }
    
    func selectingEventType() {
        isSelectingType = !isSelectingType
        let cell = self.eventVIewTableView.cellForRowAtIndexPath(NSIndexPath.init(forRow: 0, inSection: 0)) as! NewEventTextFieldCell
        cell.isSelecting = isSelectingType
        if isSelectingType{
            self.cellTitles[0].insert("type", atIndex: 1)
            self.eventVIewTableView.insertRowsAtIndexPaths([NSIndexPath.init(forRow: 1, inSection: 0)], withRowAnimation: .Top)
        }else{
            self.cellTitles[0].removeAtIndex(1)
            self.eventVIewTableView.deleteRowsAtIndexPaths([NSIndexPath.init(forRow: 1, inSection: 0)], withRowAnimation: .Top)
        }
    }
    
    func switchEndDate(isOn: Bool) {
        if  !isOn {
            timeCellHeight = 28.0
            if self.eventVIewTableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 1)) == datePickerCell {
                removeDatePickerCell()
            }
        } else {
            timeCellHeight = normalCellHeight
        }
    }
    
    func swithWholeDay(isOn: Bool) {
        if isOn {
            startTimeCell.timeBtn.hidden = true
            endTimeCell.timeBtn.hidden = true
            if isSelectingEndDate||isSelectingStartDate {
                datePickerCell.datePicker.datePickerMode = .Date
            }
        }else {
            startTimeCell.timeBtn.hidden = false
            endTimeCell.timeBtn.hidden = false
        }
    }
    
    func selectingStartDate(sender: UIButton) {
        self.view.addGestureRecognizer(resignTapGesture)
//        datePickerCell.datePicker.minimumDate = NSDate.MinDate
//        if endTimeCell.switchBtn.selected {
//            //如果末尾日期开启了,那么设置成最大的末尾日期
////            datePickerCell.datePicker.maximumDate = endDate
//        }
//        else {
//            //如果末尾日期没有开启,那么设置成最大的时间
//            datePickerCell.datePicker.maximumDate = NSDate.MaxDate
//        }

        //如果当前的开始时间大于结束时间,那么将他们设置成结束时间
//        if startDate > endDate {
//            startDate = endDate
//        }
        
        datePickerCell.datePicker.date = startDate
        
        if sender.tag == 0 {
            datePickerCell.datePicker.datePickerMode = .Date
            startTimeCell.dateBtnHighlighted = true
            startTimeCell.timeBtnHighlighted = false
        } else {
            datePickerCell.datePicker.datePickerMode = .Time
            startTimeCell.dateBtnHighlighted = false
            startTimeCell.timeBtnHighlighted = true
        }
        endTimeCell.cancelAllHighlighted()
        
        if isSelectingEndDate {
            removeDatePickerCell()
        }
        
        if !isSelectingStartDate {
            
            self.cellTitles[1].insert("datePicker", atIndex: 2)
            self.eventVIewTableView.insertRowsAtIndexPaths([NSIndexPath.init(forRow: 2, inSection: 1)], withRowAnimation: .Top)
            
            isSelectingStartDate = !isSelectingStartDate
        }
    }
    
    func selectingEndDate(sender: UIButton) {
        self.view.addGestureRecognizer(resignTapGesture)
//        
//        datePickerCell.datePicker.minimumDate = startDate
//        datePickerCell.datePicker.maximumDate = NSDate.MaxDate
//        datePickerCell.datePicker.date = endDate

        //如果开始时间大于结束时间,那么设置结束时间为开始时间
//        if startDate > endDate {
//            endDate = startDate
//        }
        
        datePickerCell.datePicker.date = endDate
        
        if sender.tag == 0 {
            datePickerCell.datePicker.datePickerMode = .Date
            endTimeCell.dateBtnHighlighted = true
            endTimeCell.timeBtnHighlighted = false
        } else {
            datePickerCell.datePicker.datePickerMode = .Time
            endTimeCell.dateBtnHighlighted = false
            endTimeCell.timeBtnHighlighted = true
        }
        startTimeCell.cancelAllHighlighted()
        
        if isSelectingStartDate {
            removeDatePickerCell()
        }
        if !isSelectingEndDate {
            self.cellTitles[1].insert("datePicker", atIndex: 3)
            self.eventVIewTableView.insertRowsAtIndexPaths([NSIndexPath.init(forRow: 3, inSection: 1)], withRowAnimation: .Top)
            isSelectingEndDate = !isSelectingEndDate
        }
    }
    
    func removeDatePickerCell() {
        if isSelectingStartDate {
            self.cellTitles[1].removeAtIndex(2)
            self.eventVIewTableView.deleteRowsAtIndexPaths([NSIndexPath.init(forRow: 2, inSection: 1)], withRowAnimation: .Top)
            isSelectingStartDate = !isSelectingStartDate
        }
        
        if isSelectingEndDate {
            self.cellTitles[1].removeAtIndex(3)
            self.eventVIewTableView.deleteRowsAtIndexPaths([NSIndexPath.init(forRow: 3, inSection: 1)], withRowAnimation: .Top)
            isSelectingEndDate = !isSelectingEndDate
        }
    }
    
    //MARK:- DatePickerDalegate
    func dateChanged(date: NSDate) {
        
        if isSelectingStartDate {
            if (date > endDate) { startDate = endDate }
            else {
                startDate = date
            }
        }
        
        if isSelectingEndDate {
            if (date < startDate) { endDate = startDate }
            else {
                endDate = date
            }
        }
    }
    
    //MARK:- EventTypeSelectedCellDelegate
    func eventTypeDidSelect(tag: Int) {
        
        self.navigationController?.navigationBar.barTintColor = YOKOColor.TypeColors[tag]
        self.eventType = tag
        self.selectingEventType()
        
    }
    
    //MARK: - UITextFieldDelegate 
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        
        return true
    }
    
    func textViewDidBeginEditing(textView: UITextView) {
        self.view.addGestureRecognizer(resignTapGesture)
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        self.view.addGestureRecognizer(resignTapGesture)
    }
    
	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}
    
    override func viewWillDisappear(animated: Bool) {
        self.navigationController?.navigationBar.barTintColor = YOKOColor.TypeColors[0]
    }
    
    //MARK:- Handler
    
    func resignTapGestureHandler() {        
        descriptionTextView.resignFirstResponder()
        locationTextField.resignFirstResponder()
        titleTextField.resignFirstResponder()
        
        startTimeCell.cancelAllHighlighted()
        endTimeCell.cancelAllHighlighted()
        
        //如果datePicker在显示状态，那么就remove掉
        if self.eventVIewTableView.cellForRowAtIndexPath(NSIndexPath(forRow: 3, inSection: 1)) == datePickerCell {
            removeDatePickerCell()
        }
        else if self.eventVIewTableView.cellForRowAtIndexPath(NSIndexPath(forRow: 2, inSection: 1)) == datePickerCell {
            removeDatePickerCell()
        }
        
        if self.eventVIewTableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 2)) == reminderCell {
            self.cellTitles[2].removeAtIndex(1)
            self.eventVIewTableView.deleteRowsAtIndexPaths([NSIndexPath.init(forRow: 1, inSection: 2)], withRowAnimation: .Top)
//            self.notifyCell.removeGestureRecognizer(resignTapGesture)
            isSelectingReminder = false
        }
        self.view.removeGestureRecognizer(resignTapGesture)
    }
    
    func deleteButtonHandler() {
        if let eventInDatabase = uiRealm.objects(Event).filter("localId = %@", event!.localId).last {
            try! uiRealm.write({
                eventInDatabase.deleted = true
            })
            
            //delete Alarm
            let fireDates = AlarmController.updateNotificationFireDate(eventInDatabase)
            if !(fireDates?.isEmpty)! {
                AlarmController.deleteAlarmWithEvent(fireDates!, wholeDayEvent: eventInDatabase.wholeDayEvent, localId: eventInDatabase.localId)
            }
            let api = ApiSync()
            api.updateEventToService(eventInDatabase, isAdd: false, calendarId: NSUserDefaults.getCurrentCalendarId(), callback: {
                (response, error) in
                print(response)
                if (response != nil && response!["result"] as! Bool == true) {
                    print(response)
                }
            })
            
            try! uiRealm.write {
                uiRealm.delete(eventInDatabase)
            }
        }
        else {
            print("\(#function) --> Cannot find localId = \(event!.localId) in database")
        }
        self.back()
    }
    
    //MARK: - ReminderCellDelegate
    func reminderDidSelected(reminder: String) {
        self.reminders = reminder
    }
}
